package org.jeecg.modules.wangyue.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wangyue.constant.*;
import org.jeecg.modules.wangyue.entity.*;
import org.jeecg.modules.wangyue.service.ICapitalFlowService;
import org.jeecg.modules.wangyue.service.IIndentJsService;
import org.jeecg.modules.wangyue.service.IProblemFeedbackService;
import org.jeecg.modules.wangyue.service.IUserRoleInfoService;
import org.jeecg.modules.wangyue.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
* @Description: 首页
* @Author: jeecg-boot
* @Date:   2023-07-24
* @Version: V1.0
*/
@Slf4j
@Api(tags="首页")
@RestController
@RequestMapping("/wangyue/sys/homePage")
@Validated
public class HomePageController {

    @Autowired
    private IUserRoleInfoService userRoleInfoService;
    @Autowired
    private IIndentJsService indentJsService;
    @Autowired
    private ICapitalFlowService capitalFlowService;
    @Autowired
    private IProblemFeedbackService problemFeedbackService;


    /**
     * 查询出首页基础数据
     *
     * @return
     */
   @AutoLog(value = "查询出首页基础数据")
   @ApiOperation(value="", notes="查询出首页基础数据")
   @GetMapping(value = "/findBasicData")
   public Result<?> findBasicData() {
       //用户人数、技师人数
       String userNum = "0";
       String jsNum = "0";
       QueryWrapper<UserRoleInfo> userRoleInfoQueryWrapper = new QueryWrapper<>();
       String userSql = "SUM(CASE WHEN user_type = '" + RoleConstant.yonghu + "' THEN 1 ELSE 0 END) as userNum";
       String jsSql = "SUM(CASE WHEN user_type = '" + RoleConstant.jishi + "' and is_role_auth = '" + IsRoleAuthConstant.yes + "' THEN 1 ELSE 0 END) as jsNum";
       userRoleInfoQueryWrapper .select( userSql + "," + jsSql);
       userRoleInfoQueryWrapper.eq("del_flag", DelFlagConstant.normal);
       Map uriMap = userRoleInfoService.getMap(userRoleInfoQueryWrapper);
       if(oConvertUtils.isNotEmpty(uriMap)){
           if(oConvertUtils.isNotEmpty(uriMap.get("userNum"))){
               userNum = uriMap.get("userNum") + "";
           }
           if(oConvertUtils.isNotEmpty(uriMap.get("jsNum"))){
               jsNum = uriMap.get("jsNum") + "";
           }
       }

       String firstDayOfThisMonth = DateUtil.getFirstDayOfmonth("yyyy-MM-dd", 0);
       String lastDayOfThisMonth = DateUtil.getLastDayOfmonth("yyyy-MM-dd", 0);
       //本月订单总数、完成订单数、未完成订单数
       String totel = "0";
       String finishNum = "0";
       String noFinishNum = "0";
       QueryWrapper<IndentJs> indentJsQueryWrapper = new QueryWrapper<>();
       String totelSql = "CAST(COUNT(order_status) AS UNSIGNED) as totel";
       String finishSql = "SUM(CASE WHEN order_status = '" + OrderStatusConstant.serviceCompletion + "' THEN 1 ELSE 0 END) as finishNum";
       String noFinishSql = "SUM(CASE WHEN order_status != '" + OrderStatusConstant.serviceCompletion + "' THEN 1 ELSE 0 END) as noFinishNum";
       indentJsQueryWrapper.select(totelSql + "," + finishSql + "," + noFinishSql);
       indentJsQueryWrapper.eq("del_flag", DelFlagConstant.normal);
       indentJsQueryWrapper.apply("create_time >= '" + firstDayOfThisMonth + "' and create_time <= '" + lastDayOfThisMonth + "'");
       Map ijMap = indentJsService.getMap(indentJsQueryWrapper);
       if(oConvertUtils.isNotEmpty(ijMap)){
           if(oConvertUtils.isNotEmpty(ijMap.get("totel"))){
               totel = ijMap.get("totel") + "";
           }
           if(oConvertUtils.isNotEmpty(ijMap.get("finishNum"))){
               finishNum = ijMap.get("finishNum") + "";
           }
           if(oConvertUtils.isNotEmpty(ijMap.get("noFinishNum"))){
               noFinishNum = ijMap.get("noFinishNum") + "";
           }
       }

       JSONObject jsonObject = new JSONObject();
       jsonObject.put("userNum", userNum); //用户总数
       jsonObject.put("jsNum", jsNum); //技师总数
       jsonObject.put("totel", totel); //订单量
       jsonObject.put("finishNum", finishNum); //完成订单
       jsonObject.put("noFinishNum", noFinishNum); //未完成订单
       return Result.OK(jsonObject);
   }


    /**
     * 查询出首页营业额
     *
     * @param firstDayOfMonth   某月第一天(yyyy-MM-dd HH:mm:ss)
     * @param lastDayOfMonth    某月最后一天(yyyy-MM-dd HH:mm:ss)
     * @return
     */
    @AutoLog(value = "查询出首页营业额")
    @ApiOperation(value="", notes="查询出首页营业额")
    @GetMapping(value = "/findTurnover")
    public Result<?> findTurnover(@RequestParam(name="firstDayOfMonth", required = true) @NotBlank(message = "月的第一天不为空") String firstDayOfMonth,
                                  @RequestParam(name="lastDayOfMonth", required = true) @NotBlank(message = "月的最后一天不为空")String lastDayOfMonth) {
        String finishIndentNum = "0";
        String finishIndentTotalAmount = "0";
        QueryWrapper<IndentJs> indentJsQueryWrapper = new QueryWrapper<>();
        String finishIndentNumSql = "COUNT(id) as finishIndentNum";
        String finishIndentTotalAmountSql = "SUM(actual_amount) as finishIndentTotalAmount";
        indentJsQueryWrapper.select(finishIndentNumSql + "," + finishIndentTotalAmountSql);
        indentJsQueryWrapper.eq("order_status", OrderStatusConstant.serviceCompletion);
        indentJsQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        indentJsQueryWrapper.apply("create_time >= '" + firstDayOfMonth + "' and create_time <= '" + lastDayOfMonth + "'");
        Map ijMap = indentJsService.getMap(indentJsQueryWrapper);
        if(oConvertUtils.isNotEmpty(ijMap)){
            finishIndentNum = ijMap.get("finishIndentNum") + "";
            if(oConvertUtils.isNotEmpty(ijMap.get("finishIndentTotalAmount"))){
                finishIndentTotalAmount = ijMap.get("finishIndentTotalAmount") + "";
            }
        }

        String withdrawalTotalAmount = "0";
        QueryWrapper<CapitalFlow> capitalFlowQueryWrapper = new QueryWrapper<>();
        String withdrawalTotalAmountSql = "SUM(change_amount) as withdrawalTotalAmount";
        capitalFlowQueryWrapper.select(withdrawalTotalAmountSql);
        capitalFlowQueryWrapper.eq("change_type", CapitalFlowTypeConstant.withdrawal);
        capitalFlowQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        capitalFlowQueryWrapper.apply("create_time >= '" + firstDayOfMonth + "' and create_time <= '" + lastDayOfMonth + "'");
        Map cfMap = capitalFlowService.getMap(capitalFlowQueryWrapper);
        if(oConvertUtils.isNotEmpty(cfMap)){
            withdrawalTotalAmount = cfMap.get("withdrawalTotalAmount") + "";
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("finishIndentNum", finishIndentNum); //订单完成量
        jsonObject.put("finishIndentTotalAmount", finishIndentTotalAmount); //订单收益金额
        jsonObject.put("withdrawalTotalAmount", withdrawalTotalAmount); //提现金额
        return Result.OK(jsonObject);
    }


    /**
     * 查询问题反馈-统计数据
     *
     * @return
     */
    @AutoLog(value = "查询问题反馈-统计数据")
    @ApiOperation(value="查询问题反馈-统计数据", notes="查询问题反馈-统计数据")
    @GetMapping(value = "/problemFeedbackStatistics")
    public Result<?> problemFeedbackStatistics() {
        String total = "0";         //反馈总数
        String finishNum = "0";     //已处理数
        String waitNum = "0";       //待处理数
        String cancelNum = "0";     //取消数
        QueryWrapper<ProblemFeedback> queryWrapper = new QueryWrapper<>();
        String totalSql = "CAST(COUNT(fb_status) AS UNSIGNED) as total";
        String finishSql = "SUM(CASE WHEN fb_status = '" + ProblemFeedbackConstant.fbStatus_complete + "' THEN 1 ELSE 0 END) as finishNum";
        String waitSql = "SUM(CASE WHEN fb_status = '" + ProblemFeedbackConstant.fbStatus_wait + "' THEN 1 ELSE 0 END) as waitNum";
        String cancelSql = "SUM(CASE WHEN fb_status = '" + ProblemFeedbackConstant.fbStatus_cancel + "' THEN 1 ELSE 0 END) as cancelNum";
        queryWrapper.select(totalSql + "," + finishSql + "," + waitSql + "," + cancelSql);
        queryWrapper.eq("del_flag", DelFlagConstant.normal);
        Map pfMap = problemFeedbackService.getMap(queryWrapper);
        if(oConvertUtils.isNotEmpty(pfMap)){
            if(oConvertUtils.isNotEmpty(pfMap.get("total"))){
                total = pfMap.get("total") + "";
            }
            if(oConvertUtils.isNotEmpty(pfMap.get("finishNum"))){
                finishNum = pfMap.get("finishNum") + "";
            }
            if(oConvertUtils.isNotEmpty(pfMap.get("waitNum"))){
                waitNum = pfMap.get("waitNum") + "";
            }
            if(oConvertUtils.isNotEmpty(pfMap.get("cancelNum"))){
                cancelNum = pfMap.get("cancelNum") + "";
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", total);
        jsonObject.put("finishNum", finishNum);
        jsonObject.put("waitNum", waitNum);
        jsonObject.put("cancelNum", cancelNum);
        return Result.OK(jsonObject);
    }


    /**
     * 查询问题反馈趋势
     *
     * @param firstDayOfMonth   月的第一天
     * @param lastDayOfMonth    月的最后一天
     * @return
     */
    @AutoLog(value = "查询问题反馈趋势")
    @ApiOperation(value="查询问题反馈趋势", notes="查询问题反馈趋势")
    @GetMapping(value = "/problemFeedbackTrend")
    public Result<?> problemFeedbackTrend(@RequestParam(name="firstDayOfMonth", required = true) @NotBlank(message = "月的第一天不为空") String firstDayOfMonth,
                                          @RequestParam(name="lastDayOfMonth", required = true) @NotBlank(message = "月的最后一天不为空") String lastDayOfMonth) {
        List<String> everyDateList = DateUtil.getEveryDayOfMonth(firstDayOfMonth); //获得该月每一天的日期yyyy-MM-dd
        if(oConvertUtils.isNotEmpty(everyDateList)){
            //查询数据库统计日期范围内每一天的问题反馈数量
            QueryWrapper<ProblemFeedback> queryWrapper = new QueryWrapper<>();
            String selectSql = "DATE_FORMAT(create_time,'%Y-%m-%d') as everyday, count(id) as num";
            queryWrapper.select(selectSql);
            queryWrapper.eq("del_flag", DelFlagConstant.normal);
            String timeSql = "create_time >= '" + firstDayOfMonth + "' and create_time <= '" + lastDayOfMonth + "'";
            queryWrapper.apply(timeSql);
            queryWrapper.groupBy("everyday");
            queryWrapper.orderByAsc("everyday");
            List<Map<String, Object>> mapList = problemFeedbackService.listMaps(queryWrapper);

            //封装数据
            List<Map<String, String>> dayList = new ArrayList<>();
            List<String> numList = new ArrayList<>();
            for(String day : everyDateList){
                String num = "0";
                for(Map map : mapList){
                    if(day.equals(map.get("everyday") + "")){
                        num = map.get("num") + "";
                        break;
                    }
                }
                Map<String, String> map = new HashMap();
                map.put("dateStr", day);
                map.put("num", num);
                dayList.add(map);
                numList.add(num);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dayList", dayList);
            jsonObject.put("numList", numList);
            return Result.OK("查询成功", jsonObject);
        }else {
            return Result.error("日期参数有问题");
        }
    }





}
